<template>
  <div class="contracts-container">
    <div class="header">
      <h2>证书名称管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="success" @click="handleExportExcel" style="margin-left: 10px;">
          <el-icon><Download /></el-icon>
          <span>导出Excel</span>
        </el-button>
      </div>
    </div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.name"
        placeholder="证书名称"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="searchForm.level" placeholder="证书级别" style="width: 150px" clearable @change="handleSearch">
        <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" v-loading="loading" :fit="true" size="small">
        <el-table-column prop="name" label="证书名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="level" label="级别" width="120">
          <template #default="scope">
            <el-tag :type="getLevelTag(scope.row.level)">{{ getLevelLabel(scope.row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="issuing_org" label="颁发机构" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增证书名称' : '编辑证书名称'" width="80%" :style="'max-width: 1200px'" top="5vh">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="contract-form">
        <div class="form-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证书名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入证书名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证书级别" prop="level">
                <el-select v-model="form.level" placeholder="请选择证书级别" style="width: 100%">
                  <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="颁发机构" prop="issuing_org">
                <el-input v-model="form.issuing_org" placeholder="请输入颁发机构" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 附件管理扩展点（如需可在此插入 AttachmentList） -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { certificateNameAPI } from '../../api'
import { getDictItemsByCode } from '../../api/dict'
import { Search, Plus, Download, Edit, Delete } from '@element-plus/icons-vue'

const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = ref({ name: '', level: '' })
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({ id: null, name: '', level: '', issuing_org: '' })
const rules = {
  name: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
  level: [{ required: true, message: '请选择证书级别', trigger: 'change' }],
  issuing_org: [{ required: true, message: '请输入颁发机构', trigger: 'blur' }]
}
const levelOptions = ref([])

const getList = async () => {
  loading.value = true
  try {
    const res = await certificateNameAPI.getAll(currentPage.value, pageSize.value, searchForm.value)
    let arr = []
    let totalCount = 0
    if (Array.isArray(res.data)) {
      arr = res.data
      totalCount = arr.length
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      tableData.value = arr.slice(start, end)
    } else if (Array.isArray(res.data.data)) {
      arr = res.data.data
      totalCount = res.data.total || arr.length
      tableData.value = arr
    } else if (Array.isArray(res.data.items)) {
      arr = res.data.items
      totalCount = res.data.total || arr.length
      tableData.value = arr
    }
    total.value = res.data.total || totalCount
  } catch (e) {
    ElMessage.error('获取证书名称列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getList()
}
const resetSearch = () => {
  searchForm.value = { name: '', level: '' }
  handleSearch()
}
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = { id: null, name: '', level: '', issuing_org: '' }
  dialogVisible.value = true
}
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该证书名称吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await certificateNameAPI.delete(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await certificateNameAPI.create(form.value)
          ElMessage.success('新增成功')
        } else {
          await certificateNameAPI.update(form.value.id, form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (e) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败')
      }
    }
  })
}
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}
const handleExportExcel = async () => {
  try {
    const res = await certificateNameAPI.exportExcel()
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '证书名称列表.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (e) {
    ElMessage.error('导出失败，请稍后重试')
    console.error('导出证书名称列表失败:', e)
  }
}
function getLevelTag(level) {
  if (level === '0') return 'success'
  if (level === '1') return 'warning'
  if (level === '2') return 'danger'
  return ''
}
function getLevelLabel(value) {
  const item = levelOptions.value.find(i => i.value === value)
  return item ? item.label : value
}
onMounted(() => {
  getList()
  getDictItemsByCode('CERT_LEVEL').then(res => {
    levelOptions.value = res.data
  })
})
</script>

<style scoped>
.contracts-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.pagination-container {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}

.contract-form {
  padding: 0 10px;
}

.form-section {
  margin-bottom: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.no-attachments-info {
  margin-top: 10px;
}

:deep(.el-table) {
  margin-bottom: 20px;
  border: none;
}

:deep(.el-table__header) {
  background-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table .el-table__fixed-right th) {
  background-color: #F5F7FA !important;
}

:deep(.el-table .el-table__fixed-right td) {
  background-color: #fff;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-button--small.is-plain) {
  background-color: #fff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:hover) {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:active) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

@media screen and (max-width: 768px) {
  .contracts-container {
    padding: 0;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  :deep(.el-form--inline .el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

.header-buttons .el-button span {
  margin-left: 4px;
}
</style> 